package com.oocl.ha.dao.impl;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.oocl.ha.dao.DishDao;
import com.oocl.ha.dao.MerchantDao;
import com.oocl.ha.entity.Dish;
import com.oocl.ha.entity.Merchant;

@Repository("dishDao")

public class DishDaoImpl implements DishDao {

	@Autowired
	private MerchantDao merchantDao;
	@PersistenceContext(name = "un")
	private EntityManager em;

	public int addDish(Dish dish, int mid) {
		try {
			Merchant merchant = merchantDao.findById(mid);
			dish.setMerchant(merchant);
			em.persist(dish);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		return 1;
	}

	public int deleteDish(int did) {
		try {
			Dish dish = findById(did);
			em.remove(dish);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		return 1;
	}

	public List<Dish> loadAllDish(int mid) {
		Merchant merchant = new Merchant();
		merchant.setMid(mid);
		String sql = "select d from Dish d where d.merchant=:merchant";		
		@SuppressWarnings("unchecked")
		List<Dish> dishs = em.createQuery(sql).setParameter("merchant", merchant).getResultList();
		if (dishs.isEmpty()) {
			return null;
		}else{
			return dishs;
		}
	}

	public Dish findById(int did) {
		Dish dish = em.find(Dish.class, did);
		return dish;
	}

	public int updateDish(Dish dish) {
		try {
			em.merge(dish);
		} catch (Exception e) {
			System.out.println("Faile to update dish.");
			return 0;
		}
		return 1;
	}

}
